import base_behavior from "../../../behavior/base_behavior";
import goodsCartService from "../../../service/goodsCart";
import {checkLogin, toLogin} from "../../../service/user";

Component({
    options:{
        styleIsolation: 'apply-shared',
    },
    behaviors:[base_behavior],
    properties: {
        list:{type:Array, value:[]},
        navigator:{type:Boolean, value:true}, // 是否可点击跳转
        liType:{
            type:String, value:'goods',	// goods-普通商品列表 cart-购物车商品列表 order-订单商品列表 shop-可操作的商品列表
        },
        showCart:{
            type:Boolean, value:true,
        },
        colNum:{type:String, value:'col_2'},
        radius:{type:String, value: 'fillet'},
    },
    data: {
        imgHeight:'',
        specShow:false,
        specGoods:null,
    },
    methods: {
        imageLoad(e){
            wx.createSelectorQuery().in(this).select(".img").boundingClientRect(res => {
                this.setData({
                    imgHeight: res.width + 'px'
                })
            }).exec();
        },
        goodsClick(e){
            const {navigator,list, liType} = this.data
            const {index} = e.currentTarget.dataset
            if(navigator && liType=='goods'){   // 只有goods类型的商品列表可以查看详情
                const id = list[index].id
                wx.navigateTo({
                    url:`/pages/goods/show?id=${id}`
                })
            }
        },

        specPopupOpen(e){

            // 没有登录，去登录页
            if (!checkLogin()){
                toLogin()
                return;
            }

            const {index} = e.currentTarget.dataset
            const {list} = this.data

            this.setData({
                specShow:true,
                specGoods:list[index],
            })
        },

        /**
         * 单规格添加购物车
         */
        numChange(e){

            // 没有登录，去登录页
            if (!checkLogin()){
                toLogin()
                return;
            }

            const {index} = e.currentTarget.dataset
            const {list} = this.data
            const goods = list[index]
            const {value} = e.detail
            let num = 0
            if (typeof value == 'undefined'){   // 点击的是[添加购物车]按钮，不是步进器
                num = 1
            }else{  // 步进器
                num = parseInt(value)
            }
            this.setData({
                [`list[${index}].num`]:num,
            })
            // 更新购物车
            goodsCartService.add({
                goods_id:goods.id,
                goods_sku_id:0,
                num: num,
            })
        },
    }
});
